// API 封装
import config from './config'

// 请求拦截器
const request = (url, options = {}) => {
    const { method = 'GET', data = {}, header = {} } = options

    // 添加token到请求头
    const token = uni.getStorageSync('token')
    if (token) {
        header['token'] = token
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url: config.baseUrl + url,
            method: method.toUpperCase(),
            data,
            header: {
                'Content-Type': 'application/json', // 默认使用json格式
                ...header
            },
            success: (res) => {
                // 统一处理响应
                if (res.statusCode === 200) {
                    const responseData = res.data;

                    // 全局处理 401 未登录状态
                    if (responseData.code === 401) {
                        console.log('检测到 401，跳转到登录页');
                        // 清空本地存储的用户信息
                        uni.removeStorageSync('token');
                        uni.removeStorageSync('member_info');

                        // 跳转到登录页
                        uni.navigateTo({
                            url: '/pages/login/login'
                        });

                        // 中断Promise链
                        return reject(responseData);
                    }

                    // 业务成功
                    if (responseData.code === 200) {
                        resolve(responseData);
                    } else {
                        // 其他业务错误
                        uni.showToast({
                            title: responseData.msg || '操作失败',
                            icon: 'none'
                        });
                        reject(responseData);
                    }
                } else {
                    // HTTP 状态码错误
                    uni.showToast({
                        title: `网络错误 ${res.statusCode}`,
                        icon: 'none'
                    });
                    reject(res);
                }
            },
            fail: (error) => {
                uni.showToast({
                    title: '请求失败，请检查网络',
                    icon: 'none'
                });
                reject(error);
            }
        })
    })
}

// API 对象
export const api = {
    // GET 请求
    get: (url, params = {}) => {
        const queryString = Object.keys(params).map(key =>
            `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
        ).join('&')

        const fullUrl = queryString ? `${url}?${queryString}` : url

        return request(fullUrl, { method: 'GET' })
    },

    // POST 请求
    post: (url, data = {}) => {
        return request(url, {
            method: 'POST',
            data
        })
    },

    // PUT 请求
    put: (url, data = {}) => {
        return request(url, { method: 'PUT', data })
    },

    // DELETE 请求
    delete: (url, data = {}) => {
        return request(url, { method: 'DELETE', data })
    }
}
